from sqlalchemy import Column, Integer, String, Boolean, DateTime, ForeignKey, Text, UniqueConstraint, Index
from datetime import datetime
from app.db.database import Base
from sqlalchemy.orm import relationship
baseconfig={
            'mysql_engine': 'InnoDB',
            'mysql_charset': 'utf8mb4',
            'mysql_collate': 'utf8mb4_unicode_ci'
        }
class Message(Base):
    __tablename__ = 'messages'
    __table_args__ = (
        Index('idx_messages_room_time', 'room_id', 'created_at'),
        baseconfig
    )
    id = Column(Integer, primary_key=True)
    type = Column(String(20))  # text/file/image
    content = Column(Text)    # 文本内容或文件描述
    file_path = Column(String(255))  # 文件路径
    file_size = Column(Integer)
    sender_id = Column(Integer, ForeignKey('users.id'), nullable=False)
    room_id = Column(Integer, ForeignKey('rooms.id'))
    status = Column(Integer, default=0)  # 0-发送中 1-成功 2-失败
    created_at = Column(DateTime, default=datetime.now, index=True)


class Room(Base):
    __tablename__ = 'rooms'
    __table_args__ = (
        Index('idx_rooms_name', 'name'),
        baseconfig
    )
    
    id = Column(Integer, primary_key=True)
    name = Column(String(50), nullable=False)
    avatar = Column(String(255), default='')
    creator_id = Column(Integer, ForeignKey('users.id'), nullable=False)  # 这是群主ID
    type = Column(Integer, default=0)  # 添加类型字段：0-私聊，1-群聊
    member_count = Column(Integer, default=0)
    last_msg_time = Column(DateTime)
    created_at = Column(DateTime, default=datetime.now)
    description = Column(String(255), default='')
    creator = relationship("User")  # 这个关系映射到群主
    members = relationship("RoomMember", back_populates="room")

class RoomMember(Base):
    __tablename__ = 'room_members'
    __table_args__ = (
        UniqueConstraint('room_id', 'user_id', name='uix_room_user'),
        Index('idx_room_member', 'room_id', 'user_id'),
        baseconfig
    )
    
    id = Column(Integer, primary_key=True)
    room_id = Column(Integer, ForeignKey('rooms.id'), nullable=False)
    user_id = Column(Integer, ForeignKey('users.id'), nullable=False)
    nickname = Column(String(50), default='')
    role = Column(Integer, default=0)  # 0-成员 1-管理员 2-群主
    created_at = Column(DateTime, default=datetime.now)

    room = relationship("Room", back_populates="members")

    user = relationship("User")  # 修改为字符串形式